use lazy_static::lazy_static;
use std::sync::MutexGuard;
use std::sync::Mutex;
use async_std::{task, channel};
use async_std::channel::{Receiver, Sender, RecvError};
use async_std::task::JoinHandle;
use futures::TryFutureExt;
use std::time::Instant;
lazy_static! {
    pub static ref VEC : Mutex<Vec<i32>> = Mutex::new(Vec::<i32>::new());
}

pub fn vec() -> MutexGuard<'static, Vec<i32>> {
    VEC.lock().unwrap()
}

pub fn init() -> (Sender<Box<dyn Fn(&mut Vec<i32>) + Send + Sync>>, JoinHandle<()>) {
    let (s, r) =
        channel::bounded::<Box<dyn Fn(&mut Vec<i32>) + Send + Sync>>(100);
    let handle = task::spawn(do_func(r));
    (s, handle)
}

async fn do_func(r: Receiver<Box<dyn Fn(&mut Vec<i32>) + Send + Sync>>) {
    let mut v = Vec::<i32>::new();
    let ins = Instant::now();
    loop {
        let func = r.recv().await.unwrap();
        func(&mut v);
        println!(" v : {:?}", v);
        println!(" time : {} ms", ins.elapsed().as_millis() );
    }
}